// Copyrights 2021 WU PENG. All rights reserved.
//

#include "max7219.h"

#include <ESP8266WiFi.h>
#include <TZ.h>

const char * ssid     = "TP-LINK_FFF6";
const char * password = "c8sv4qPH";

const char months[12][4] = {
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec",
};

const char weekdays[7][4] = {
  "Sun",
  "Mon",
  "Tue",
  "Wed",
  "Thu",
  "Fri",
  "Sat",
};

// IO2 -> DIN
// IO0 -> CS
// IO4 -> CLK
Max7219 max7219(2, 0, 4, 4);

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.println("Starting...");

  max7219.begin();
  max7219.ClearBuffer();
  max7219.DrawText(0, 'W');
  max7219.DrawText(6, 'a');
  max7219.DrawText(11, 'i');
  max7219.DrawText(16, 't');
  max7219.Flush();

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("IP: ");
  Serial.println(WiFi.localIP());
  
  configTime(TZ_Asia_Shanghai, "cn.pool.ntp.org");
}

void loop() {
  static int i = 0;

  time_t t = time(NULL);
  struct tm * tt = localtime(&t);

  switch (i++%10) {
  case 8:
    max7219.DrawText(0, weekdays[tt->tm_wday][0]);
    max7219.DrawText(6, weekdays[tt->tm_wday][1]);
    max7219.DrawText(12, weekdays[tt->tm_wday][2]);
    max7219.DrawText(18, ' ');
    max7219.DrawText(24, ' ');
    max7219.DrawText(30, ' ');
    max7219.Flush();
    delay(2000);
    break;
  case 9:
    max7219.DrawText(0, months[tt->tm_mon][0]);
    max7219.DrawText(6, months[tt->tm_mon][1]);
    max7219.DrawText(12, months[tt->tm_mon][2]);
    max7219.DrawText(18, ' ');
    max7219.DrawText(21, tt->tm_mday/10+'0');
    max7219.DrawText(27, tt->tm_mday%10+'0');
    max7219.Flush();
    delay(2000);
    break;
  default:
    max7219.DrawText(0, tt->tm_hour/10+'0');
    max7219.DrawText(5, tt->tm_hour%10+'0');
    max7219.DrawText(11, tt->tm_min/10+'0');
    max7219.DrawText(16, tt->tm_min%10+'0');
    max7219.DrawText(22, tt->tm_sec/10+'0');
    max7219.DrawText(27, tt->tm_sec%10+'0');
    max7219.Flush();
    delay(1000);
  }
}
